package com.loren.demo10.context;

import com.loren.demo10.aspect.SupportScript;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;

@Slf4j
@Component
@AllArgsConstructor
public class CustomAnnotationContext implements InitializingBean {

    private final ApplicationContext applicationContext;

    @Override
    public void afterPropertiesSet() {
        Map<String, Object> services = this.applicationContext.getBeansWithAnnotation(Service.class);
        Collection<Object> serviceClasses = services.values();
        for (Object serviceClass : serviceClasses) {
            Class<?> clazz = AopUtils.getTargetClass(serviceClass);
            Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
            for (Method method : methods) {
                if (method.isAnnotationPresent(SupportScript.class)) {
                    SupportScript script = method.getAnnotation(SupportScript.class);
                    log.info("clazz = {}, method = {}, value = {}, label = {}", clazz.getName(), method.getName(), script.value(), script.label());
                }
            }
        }
    }
}
